from datetime import datetime
from app import db

class Task(db.Model):
    """待办事项模型"""
    __tablename__ = 'tasks'
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text)
    priority = db.Column(db.Enum('low', 'medium', 'high', name='priority_enum'), 
                        default='medium', nullable=False)
    status = db.Column(db.Enum('todo', 'in_progress', 'completed', name='status_enum'), 
                      default='todo', nullable=False)
    due_date = db.Column(db.Date)
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, 
                          onupdate=datetime.utcnow, nullable=False)
    
    def __repr__(self):
        return f'<Task {self.title}>'
    
    def to_dict(self):
        """将模型转换为字典"""
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'priority': self.priority,
            'status': self.status,
            'due_date': self.due_date.isoformat() if self.due_date else None,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }
    
    @property
    def is_completed(self):
        """检查任务是否已完成"""
        return self.status == 'completed'
    
    @property
    def is_overdue(self):
        """检查任务是否已过期"""
        if self.due_date and not self.is_completed:
            return self.due_date < datetime.now().date()
        return False
    
    def mark_completed(self):
        """标记任务为已完成"""
        self.status = 'completed'
        self.updated_at = datetime.utcnow()
    
    def mark_in_progress(self):
        """标记任务为进行中"""
        self.status = 'in_progress'
        self.updated_at = datetime.utcnow()